package com.xindaoapp.henghua.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.library.utils.IRequest;
import com.library.utils.KeyValuePair;
import com.library.utils.ThreadPool;
import com.library.utils.VolleyLog;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.util.RequestQueue;
import com.xindaoapp.henghua.application.XinDaoApplication;
import com.xindaoapp.henghua.entry.PropertyLabelInfo;
import com.xindaoapp.henghua.entry.ScanData;
import com.xindaoapp.henghua.entry.UnSubmitLabelInfo;

/**
 * 上传文件
 * @author chenghao
 *
 */
public class UploadFile {

	public static void upload(Context context, final Header[] headers,
			List<KeyValuePair<String, File>> files, String packageName, String versionName) {
		RequestParams requestParams = new RequestParams();
		for (KeyValuePair<String, File> file : files) {
			if (file.second.exists()) {
				requestParams.put(file.first, new FileBody(file.second));
			}
		}
		for (Header header : headers) {
			requestParams.put(header.getName(), header.getValue());
		}

		RequestQueue.client.addHeader("giipVersion", "3.0");
		RequestQueue.client.addHeader("udid", XinDaoApplication.get().getUserInfo().udid);
		RequestQueue.client.addHeader("appVersion", versionName);
		RequestQueue.client.addHeader("appName", packageName);

		try {
			RequestQueue.client.post(context, "http://t1.hhwy.org/giipms/service?m=trace_upsupervisiondatas",
					headers, requestParams.getEntity(null), HTTP.UTF_8, new AsyncHttpResponseHandler() {

						@Override
						public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
							VolleyLog.e("statusCode：%s, %s", statusCode, new String(responseBody));
						}

						@Override
						public void onFailure(int statusCode, Header[] headers, byte[] responseBody,
								Throwable error) {
							VolleyLog.e("statusCode：%s, %s", statusCode, new String(responseBody));
							VolleyLog.e("getMessage：%s", error.getMessage());
						}
					});
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 上传图片
	 * @param files
	 * @param headers
	 */
	public static void uploadFile(final List<KeyValuePair<String, File>> files, final Header[] headers,
			final IRequest<Boolean> iRequest, final String packageName, final String versionName) {
		ThreadPool.addRunnable(new Runnable() {

			@Override
			public void run() {
				HttpClient httpclient = new DefaultHttpClient();
				// 设置通信协议版本
				httpclient.getParams()
						.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

				String urlServer = "http://t1.hhwy.org/giipms/service?m=trace_upsupervisiondatas";

				HttpPost httppost = new HttpPost(urlServer);
				httppost.addHeader("giipVersion", "3.0");
				httppost.addHeader("udid", XinDaoApplication.get().getUserInfo().udid);
				httppost.addHeader("appVersion", versionName);
				httppost.addHeader("appName", packageName);

				MultipartEntity mpEntity = new MultipartEntity(); // 文件传输
				for (Header header : headers) {
					try {
						mpEntity.addPart(header.getName(),
								new StringBody(header.getValue(), Charset.forName("UTF-8")));
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}

				for (KeyValuePair<String, File> file : files) {
					if (file.second.exists()) {
						mpEntity.addPart(file.first, new FileBody(file.second));
					}
				}
				httppost.setEntity(mpEntity);
				System.out.println("executing request " + httppost.getRequestLine());
				try {
					HttpResponse response = httpclient.execute(httppost);

					StatusLine status = response.getStatusLine();
					byte[] responseBody;
					responseBody = getResponseData(response.getEntity());
//					JSON.parseObject(responseBody, clazz);
					// additional cancellation check as getResponseData() can
					// take non-zero time to process
					VolleyLog.e(new String(responseBody).toString());
					if (!Thread.currentThread().isInterrupted()) {
						if (status.getStatusCode() == 200) {
							XinDaoApplication.getHandler().post(new Runnable() {

								@Override
								public void run() {
									iRequest.request(true);
								}
							});
//							sendFailureMessage(
//									status.getStatusCode(),
//									response.getAllHeaders(),
//									responseBody,
//									new HttpResponseException(status.getStatusCode(), status
//											.getReasonPhrase()));
						} else {
							XinDaoApplication.getHandler().post(new Runnable() {

								@Override
								public void run() {
									iRequest.request(false);
								}
							});
//							sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
						}
					}
					
//					VolleyLog.e("upload status code ： %s", response.getStatusLine().getStatusCode());
				} catch (ClientProtocolException e) {
					e.printStackTrace();
					XinDaoApplication.getHandler().post(new Runnable() {

						@Override
						public void run() {
							iRequest.request(false);
						}
					});
				} catch (IOException e) {
					e.printStackTrace();
					XinDaoApplication.getHandler().post(new Runnable() {

						@Override
						public void run() {
							iRequest.request(false);
						}
					});
				} finally {
					httppost.abort();
				}
			}
		});
	}

	protected static final int BUFFER_SIZE = 4096;

	static byte[] getResponseData(HttpEntity entity) throws IOException {
		byte[] responseBody = null;
		if (entity != null) {
			InputStream instream = entity.getContent();
			if (instream != null) {
				long contentLength = entity.getContentLength();
				if (contentLength > Integer.MAX_VALUE) {
					throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
				}
				int buffersize = (contentLength < 0) ? BUFFER_SIZE : (int) contentLength;
				try {
					ByteArrayBuffer buffer = new ByteArrayBuffer(buffersize);
					try {
						byte[] tmp = new byte[BUFFER_SIZE];
						int l, count = 0;
						// do not send messages if request has been cancelled
						while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
							count += l;
							buffer.append(tmp, 0, l);
//							sendProgressMessage(count, (int) contentLength);
						}
					} finally {
						instream.close();
					}
					responseBody = buffer.toByteArray();
				} catch (OutOfMemoryError e) {
					System.gc();
					throw new IOException("File too large to fit into available memory");
				}
			}
		}
		return responseBody;
	}

	public static String getJson(List<UnSubmitLabelInfo> list) {
		JSONArray content_json = new JSONArray();

		for (UnSubmitLabelInfo info : list) {
			JSONObject jo = new JSONObject();
			try {
				JSONArray asserttag = new JSONArray();
				JSONObject asobj = new JSONObject();
				asobj.put("id", info.propertyLabelInfo.id);
				asobj.put("tag_code", info.propertyLabelInfo.tag_code);
				asobj.put("part", info.propertyLabelInfo.part);
				asobj.put("create_time", info.propertyLabelInfo.create_time);
				asserttag.put(0, asobj);

				JSONArray supervision = new JSONArray();
				JSONObject suobj = new JSONObject();
				suobj.put("id", info.propertyLabelInfo.id);// 贴标签信息表表中记录的唯一id(uuid)
				suobj.put("notes", "");
				supervision.put(0, suobj);

				JSONArray scan = new JSONArray();
				JSONObject scanobj = new JSONObject();
				scanobj.put("id", info.scanData.id);
				scanobj.put("tag_code", info.scanData.tag_code);
				scanobj.put("scan_time", info.scanData.scan_time);
				scanobj.put("scan_location_gps", info.scanData.scan_location_gps);
				scanobj.put("scan_location", info.scanData.scan_location);
				scanobj.put("scan_device", info.scanData.scan_device);
				scanobj.put("scan_devicename", info.scanData.scan_devicename);
				scanobj.put("scan_userid", info.scanData.scan_userid);
				scanobj.put("scan_username", info.scanData.scan_username);
				scanobj.put("scan_status", info.scanData.status);

				JSONObject photos = new JSONObject();
				JSONArray bre = new JSONArray();
				if (null != info.scanData.photos.breviaryphotos) {
					for (int i = 0; i < info.scanData.photos.breviaryphotos.size(); i++) {
						bre.put(i, getPhotoName(info.scanData.photos.breviaryphotos.get(i)));
					}
				}

				JSONArray pho = new JSONArray();
				if (null != info.scanData.photos.photphotos) {
					for (int i = 0; i < info.scanData.photos.photphotos.size(); i++) {
						pho.put(i, getPhotoName(info.scanData.photos.photphotos.get(i)));
					}
				}

				photos.put("breviaryphotos", bre);
				photos.put("photphotos", pho);

				scanobj.put("photos", photos);

				scan.put(0, scanobj);

				JSONObject data = new JSONObject();
				data.put("asserttag", asserttag);
				data.put("supervision", supervision);
				data.put("scan", scan);

				jo.put("data", data);
				jo.put("assert_id", info.propertyLabelInfo.assert_id);

				content_json.put(jo);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		return content_json.toString();
	}

	public static String getJson(PropertyLabelInfo propertyLabelInfo, ScanData scanData) {
		UnSubmitLabelInfo info = new UnSubmitLabelInfo();
		info.propertyLabelInfo = propertyLabelInfo;
		info.scanData = scanData;

		List<UnSubmitLabelInfo> list = new ArrayList<UnSubmitLabelInfo>();
		list.add(info);
		return getJson(list);
	}

	public static String getPhotoName(String path) {

		File file = new File(path);

		return file.getName();

	}
}
